define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');

	var info = {
		click: 'javascript:;',
		url: '',
		track: '',
		width: 400,
		height: 100,
		base: '/resources/swf/',
		logo: 1,
		content:''
	};

	var encode = encodeURIComponent;
	var CDN_HOST = 'http://stuff.cdn.biddingx.com';

	// 生成Flash代码
	var flashCode = function (arg) {
		var param = {
			quality: 'high',
			align: 'middle',
			menu: 'false',
			wmode: 'transparent'
		};
		var i,j;
		for (i in arg){
			if (arg.hasOwnProperty(i)){
				param[i] = arg[i];
			}
		}
		var prop = ',width,height,hspace,vspace,align,class,id,name,style,';
		var code = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" type="application/x-shockwave-flash" ';
		var embed = '<embed src="' + param.swf + '" type="application/x-shockwave-flash" ';
		var tags = '<param name="movie" value="' + param.swf + '">';
		delete param.swf;

		for (i in param){
			if (param.hasOwnProperty(i)){
				j = i + '="' + param[i] + '" ';
				if (prop.indexOf(','+i+',') < 0){
					tags += '<param name="' + i + '" value="' + param[i] + '">';
				}else {
					code += j;
				}
				embed += j;
			}
		}

		return (code + '>' + tags + embed + '></embed></object>');
	};

	// 生成广告展示代码
	var showAd = function(url){
		var html = '<div class="vp" id="{$id}VP">';
		switch (url.toLowerCase().slice(-4)){
			case '.swf':
				html += flashCode({'swf':url, 'width':info.width, 'height':info.height});
				break;
			case '.mp4':
			case '.flv':
				html += flashCode({
					'swf':'{$base}player.swf',
					'flashvars':'video='+encode(url),
					'scale':'noscale', 'width':info.width, 'height':info.height
				});
				break;
			default:
				html += '<img src="{$url}" width="{$width}" height="{$height}" border="0"/>';
				if(info.content){
					html += '<div class="ptxContent">{$content}</div>';
				}
				break;
		}
		html += '</div>';
		return html;
	};

	// 替换变量功能函数
	var replaceExt = function (code){
		return code.replace(/%%BDX_EXT%%/g, info.bdx_ext)
				.replace(/%%BDX_EXT_ENC%%/g, encode(info.bdx_ext))
				.replace(/%%BDX_HOST%%/g, CDN_HOST);
	}
	var replaceVar = function(code){
		return code.replace(/\{\$(\w+)\}/g, function(m,name){
			return info[name]||'';
		});
	}

	var setPreviewContent = function(creative){
		switch (creative.Type){
			case 1:
				//图文创意,显示主素材
			case 6:
			case 2:
				info.url = '/'+creative.Path;
				break;
			case 3:
				info.url = creative.Path;
				break;
			case 4:
				break;
			default:
				pubjs.alert('创意类型暂时不支持预览(type:'+ creative.Type + ')');
				return false;
		}
		info.width = creative.Width || info.width;
		info.height = creative.Height || info.height;
		info.content = '';

		var html = '';
		if (creative.Type == 4) {
			//代码创意
			var previewUrl = "/api/admin/creativeAudit/showCodeCreative?id=" + creative._id;
			html = '<iframe src="'+ previewUrl + '" frameBorder="0" height="'+ creative.Height+'" width="'+creative.Width+'"></iframe>';
		} else{
			if(creative.Type == 6) {
				//图文创意，输出内容
				if(!creative.fields){
					creative.fields = [];
				}
				for(var i = 0; i < creative.fields.length; i++){
					var f = creative.fields[i];
					var text = f.content;
					switch (f.type){
						case 2:
							//图片
							var thumb = f.upload && f.upload.thumb;
							text = `<img style="max-width: 200px;" title="${thumb? '': '图片缩略图不存在'}" src="${thumb? f.upload.thumb: ''}"/>`;
							break;
						case 4:
							//radio类型
							for(var j= 0; j< f.options.length; j++){
								if(f.options[j].value == f.content){
									text = f.options[j].name;
								}
							}
					}
					info.content += '<p><span class="ptxContentLabel">'+ f.title  + ':</span><b class="ml10 mb10">' + text + '</b>'+'</p>';
				}
			}

			html = showAd(info.url);
		}
		html = replaceExt(replaceVar(html));

		return html;
	}

	var showInfo = function (moduleName,eventObj,displayHtml,cssObj) {
		var self = this;
		var tip  = self.get(moduleName);
		var el = $(eventObj.target);
		cssObj = cssObj || {};
		var windowWidth = cssObj.width || 200 ;
		if(!tip){
			tip = self.createAsync(moduleName, '@base/tip.base', {
				'class':'P-creativeAuditInfo',
				'pos': cssObj.pos||'tR',
				'anchor': el,
				'delayHide': 500,
				'autoHide':'click',
				"autoShow": false,
				"drag": false
			}, function(mod){
				tipBody = mod.getContainer();
				tipBody.html(displayHtml).css({'width': windowWidth});
				mod.show();
			});
		} else {
			tipBody = tip.getContainer();
			tipBody.html(displayHtml).css({'width': windowWidth});
			tip.update({anchor: el, pos: cssObj.pos || "tR"});
			tip.show();
		}
	}

	var showPreviewImage = function(ev){
		var self = this;
		var tip  = self.get('previewImage');
		var el = $(ev.target);
		var data = $(ev.target).data();

		switch (ev.type){
			case 'click':
				var tipBody;
				// 计算tip显示的位置，如果下方不够现实则在上方显示
				var clientY = ev.clientY;
				var viewport = util.getViewport();
				var h = viewport.height - clientY - 50;
				var w = viewport.width - ev.clientX - 50;

				//弹窗位置
				var pos, posY = 'b',posX = 'm';
				if (h < 250) {
					posY = 't'
				}
				if (w > 700 ) {
					posX = 'L';
				}
				pos = posY + posX;

				var windowWidth = data.Type  == 6 ?  Math.max(300,data.Width + 20):data.Width+20;
				var html = setPreviewContent(data);
				if(!html){
					return false;
				}
				//弹出框
				if (!tip){
					tip = self.createAsync('previewImage', '@base/tip.base', {
						'target': pubjs.DEFAULT_POPUP_CONTAINER,
						'class':'P-creativeAudit',
						'pos': pos,
						'anchor': el,
						'delayHide': 100,
						'autoHide':'click',
						"autoShow": false,
						"drag": false
					}, function(mod){
						tipBody = mod.getContainer();
						tipBody.html(html).css({'width':  windowWidth });
						mod.show();
					});
				}else {
					tipBody = tip.getContainer();
					tipBody.html(html).css({'width': windowWidth});
					tip.update({anchor: el, pos: pos});
					tip.show();
				}
				break;
			case 'click':
				if (tip){ tip.hide(); }
				break;
			case 'imageLoad':
				el.attr('data-ready', '1');
				break;
			case 'imageError':
				el.attr('data-thumb', null);
				break;
		}
	}

	var showAptitudeData = {
		getAptitudeData: function(creativeId,aptitudeId){

			if(!this.$aptitudeMap || this.$aptitudeMapCount > 200){
				//清空缓存
				this.$aptitudeMap = {};
				this.$aptitudeMapCount = 0;
			}
			var key = `${creativeId}_${aptitudeId}`;

			if(!this.$aptitudeMap[key]){
				pubjs.loading.show();
				var url = this.getConfig('getAptitudeInfoUrl');
				pubjs.mc.send(url, {creativeId:creativeId,aptitudeId:aptitudeId}, this.onGetAptitudeData.bind(this));
			} else {
				this.showAptitudeInfoHtml(this.$aptitudeMap[key]);
			}

		},
		onGetAptitudeData: function(err, data){
			pubjs.loading.hide();
			if(err){
				pubjs.alert(err.message);
				return false;
			} else if(!data.success){
				pubjs.alert(data.message|| LANG("未知错误"));
				return false;
			}

			this.$aptitudeMap[data.data.CreativeId + '_' + data.data._id] = data.data;
			this.$aptitudeMapCount ++;
			this.showAptitudeInfoHtml(data.data);
		},
		showAptitudeInfoHtml:function (data) {

			var html = `<p>资质:${data.UserName}(ID:${data._id})</p>
								<table class="auditCreative-aptitudeInfo">
								<tr><td>渠道</td><td>审核情况</td><td>资质行业分类</td><td>活动ID</td><td>活动广告(行业)分类</td><td>活动敏感分类</td></tr>`;

			var AptitudeStatusMap = {
				'-2':'审核中',
				'-1':'不通过',
				'0':'初始化，未上传',
				'1':'通过',
				'2':'部分通过'
			};

			for(var i = 0; i < data.Info.length ; i++){
				var info = data.Info[i];
				html += `<tr><td>${info.ExchangeName}</td>
									<td>${AptitudeStatusMap[info.Status] || '--'}</td>
									<td>${info.IndustryName || '--'}</td>
									<td style="${info.inUseCampaign && info.inUseCampaign.IsDeleted ? 'text-decoration:line-through;color:red':''}">
										${info.inUseCampaign ? info.inUseCampaign._id : '--'}
									</td>
									<td>${info.inUseCampaign && info.inUseCampaign._AdCategoryNames ?info.inUseCampaign._AdCategoryNames : ['--'] }</td>
									<td>${info.inUseCampaign && info.inUseCampaign._AdSensitiveNames ?info.inUseCampaign._AdSensitiveNames : ['--'] }</td></tr>`;
			}

			html += '</table>';

			//生成展示的html
			if(this.$showAptitudeInfoEventTarget){
				showInfo.call(this,'previewAptitudeInfo',this.$showAptitudeInfoEventTarget,html,{width:'auto',pos:this.$showAptitudeRowIndex < 5? 'bR':'tR'});
			}
		},
		clearAptitudeDataCache:function(){
			this.$aptitudeMap = {};
			this.$aptitudeMapCount = 0;
		}
	};

	exports.showAptitudeData = showAptitudeData;
	exports.showInfo = showInfo;
	exports.showPreviewImage = showPreviewImage;
});